<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item>
          <el-input
            v-model="queryParams.order_no"
            placeholder="请输入订单号"
            clearable
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.member_keyword"
            placeholder="请输入会员姓名/手机号"
            clearable
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.partner_id"
            placeholder="选择商家"
            clearable
            @clear="handleQuery"
          >
            <el-option
              v-for="item in partnerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.status"
            placeholder="订单状态"
            clearable
            @clear="handleQuery"
          >
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="已退款" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryParams.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        border
      >
        <el-table-column prop="order_no" label="订单号" width="180" />
        <el-table-column prop="member_name" label="会员姓名" width="120" />
        <el-table-column prop="member_phone" label="会员手机号" width="120" />
        <el-table-column prop="partner.name" label="商家名称" width="150" />
        <el-table-column prop="product_name" label="产品名称" min-width="150" />
        <el-table-column prop="amount" label="消费金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ orderStatus[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="confirm_at" label="确认时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              link
              @click="handleConfirm(scope.row)"
            >
              确认
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              link
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="success"
              link
              @click="handleComplete(scope.row)"
            >
              完成
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              type="warning"
              link
              @click="handleRefund(scope.row)"
            >
              退款
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号" :span="2">{{ detail.order_no }}</el-descriptions-item>
        <el-descriptions-item label="会员姓名">{{ detail.member_name }}</el-descriptions-item>
        <el-descriptions-item label="会员手机号">{{ detail.member_phone }}</el-descriptions-item>
        <el-descriptions-item label="商家名称">{{ detail.partner?.name }}</el-descriptions-item>
        <el-descriptions-item label="消费金额">¥{{ detail.amount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="产品名称" :span="2">{{ detail.product_name }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(detail.status)">
            {{ orderStatus[detail.status] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="服务人员">{{ detail.employee?.name }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="确认时间">{{ detail.confirm_at }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ detail.complete_at }}</el-descriptions-item>
        <el-descriptions-item label="退款时间">{{ detail.refund_at }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const detailDialogVisible = ref(false)
const orderList = ref([])
const total = ref(0)
const detail = ref({})
const partnerOptions = ref([])

// 订单状态
const orderStatus = {
  0: '待确认',
  1: '已确认',
  2: '已完成',
  3: '已取消',
  4: '已退款'
}

// 状态对应的标签类型
const getStatusType = (status) => {
  const map = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return map[status]
}

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const queryParams = reactive({
  page: 1,
  limit: 10,
  order_no: '',
  member_keyword: '',
  partner_id: '',
  status: '',
  date_range: []
})

// 获取商家列表
const getPartnerList = async () => {
  try {
    const res = await request.get('/partner/list', { params: { limit: 999 } })
    partnerOptions.value = res.data.list
  } catch (error) {
    console.error(error)
  }
}

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/order/consume/list', {
      params: {
        ...queryParams,
        start_date: queryParams.date_range?.[0],
        end_date: queryParams.date_range?.[1]
      }
    })
    orderList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error(error)
  }
  loading.value = false
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 导出
const handleExport = async () => {
  try {
    const res = await request.get('/order/consume/export', {
      params: {
        ...queryParams,
        start_date: queryParams.date_range?.[0],
        end_date: queryParams.date_range?.[1]
      },
      responseType: 'blob'
    })
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '消费订单列表.xlsx'
    link.click()
  } catch (error) {
    console.error(error)
  }
}

// 确认订单
const handleConfirm = (row) => {
  ElMessageBox.confirm('确认该订单？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/order/consume/confirm', { id: row.id })
      ElMessage.success('确认成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该订单？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/order/consume/cancel', { id: row.id })
      ElMessage.success('取消成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 完成订单
const handleComplete = (row) => {
  ElMessageBox.confirm('确认完成该订单？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/order/consume/complete', { id: row.id })
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 退款
const handleRefund = (row) => {
  ElMessageBox.confirm('确认对该订单进行退款？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/order/consume/refund', { id: row.id })
      ElMessage.success('退款成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 查看详情
const handleDetail = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

onMounted(() => {
  getPartnerList()
  getList()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 